<template>
  <div class="multi-input">
    <el-tag v-for="(tag, index) in dynamicTags"
            :key="index" closable size="large"
            :disable-transitions="false" @close="handleClose(tag)">
      {{ tag }}
    </el-tag>
    <el-input v-if="inputVisible"
              ref="InputRef" v-model="inputValue"
              placeholder="请输入内容"
              show-word-limit :maxlength="props.inputLength" clearable
              @keyup.enter="handleInputConfirm" @blur="handleInputConfirm"
              style="width: 10vw"/>
    <el-button v-else type="primary" @click="showInput">新增</el-button>
  </div>
</template>

<script lang="ts" setup>
import { computed, defineProps, nextTick, PropType, ref } from 'vue'
import { ElMessage } from 'element-plus'
import type { InputInstance } from 'element-plus'

const inputValue = ref('')
const inputVisible = ref(false)
const InputRef = ref<InputInstance>()

const props = defineProps({
  data: {
    required: true,
    type: Array as PropType<string[]>
  },
  size: {
    default: 3,
    type: Number
  },
  inputLength: {
    default: 10,
    type: Number
  }
})

const dynamicTags = computed(() => props.data as string[])

const handleClose = (tag: string) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}

const handleInputConfirm = () => {
  if (inputValue.value) {
    if (props.size > 0 && dynamicTags.value.length + 1 > props.size) {
      ElMessage.error(`最多添加${props.size}个`)
    } else {
      dynamicTags.value.push(inputValue.value)
    }
  }
  inputVisible.value = false
  inputValue.value = ''
}
</script>

<style lang="scss">
.multi-input {
  display: flex;
  gap: 0.5vw;
}
</style>
